﻿Public Class TextLanguageAnalysis
    'This implementation is VERY simplified and need future attension to 
    'support more language, possibly utilizing webservices to solve this
    'issue

    Public Enum Language
        Swedish
        English
        Unknown
    End Enum

    Public Shared Function GetLanguageOfFile(ByVal textFilePath As String) As Language
        Dim strText As String = Framework.IO.Utils.ReadTextFile(textFilePath).ToLower.Replace(vbCrLf, " ")
        Return GetLanguageOfText(strText)
    End Function
    Public Shared Function GetLanguageOfText(ByVal text As String) As Language
        If IsMostLikelyEnglish(text) Then
            Return Language.English
        ElseIf IsMostLikelySwedish(text) Then
            Return Language.Swedish
        Else
            Return Language.Unknown
        End If
    End Function

    Private Shared Function IsMostLikelyEnglish(ByVal text As String) As Boolean
        If CountScore(text, "he", "she", "it", "was", "is", "hello", "bye") >= 4 Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Shared Function IsMostLikelySwedish(ByVal text As String) As Boolean
        If CountScore(text, "han", "hon", "de", "är", "gör", "hej", "då") >= 4 Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Shared Function CountScore(ByVal text As String, ByVal ParamArray keyWords() As String) As Integer
        Dim aKeyWords As New Generic.Dictionary(Of String, String)
        For Each strKeyWord As String In keyWords
            aKeyWords.Add(strKeyWord.ToLower, Nothing)
        Next
        Dim aWordsInFile() As String = text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
        Dim iScore As Integer = 0
        For Each strWord As String In aWordsInFile
            If aKeyWords.ContainsKey(strWord) Then
                iScore += 1
                aKeyWords.Remove(strWord)
            End If
        Next
        Return iScore
    End Function
End Class
